<script setup>
import { onMounted, ref, watch, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { billMoneyDataService, billAmountDataService } from '@/api/bill'

const money = ref()

const moneyOption = ref({
  visualMap: {
    show: false,
    type: 'continuous',
    seriesIndex: 0,
    min: 0,
    max: 2000
  },
  title: {
    left: 'center',
    text: '账单金额统计'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      label: {
        backgroundColor: '#6a7985'
      }
    }
  },
  toolbox: {
    feature: {
      saveAsImage: {}
    }
  },
  grid: {
    left: '5%',
    right: '5.5%',
    bottom: '5%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: '' // 设置日期数组
  },
  yAxis: {
    type: 'value'
  },
  series: {
    name: '金额',
    type: 'line',
    areaStyle: {},
    data: '' // 设置金额数组
  }
})

const moneyDate = ref(new Date().setHours(0, 0, 0, 0))
const moneyRange = ref(7)

const moneyChart = ref()

const getMoneyData = async () => {
  // 图表加载中样式
  moneyChart.value.showLoading()

  const response = await billMoneyDataService({
    createTime: moneyDate.value,
    range: moneyRange.value
  })
  moneyOption.value.xAxis.data = response.data.map((item) => {
    let date = new Date(item.date)
    // 提取年、月、日
    let year = date.getFullYear()
    let month = (1 + date.getMonth()).toString().padStart(2, '0') // 月份是从0开始的，所以需要加1，并用0填充到两位数
    let day = date.getDate().toString().padStart(2, '0') // 用0填充到两位数

    // 拼接成YYYY-MM-DD格式
    return `${year}-${month}-${day}`
  })
  moneyOption.value.series.data = response.data.map((item) => item.cost)

  var range = () => {
    if (moneyRange.value === 7) {
      return '一周内'
    } else if (moneyRange.value === 14) {
      return '两周内'
    } else if (moneyRange.value === 30) {
      return '一个月内'
    }
  }
  moneyOption.value.title.text = `账单金额统计--${range()}`
  moneyChart.value.hideLoading()
  moneyChart.value.setOption(moneyOption.value)
}

watch(moneyRange, async () => {
  await getMoneyData()
})

watch(moneyDate, async (newValue) => {
  if (newValue === null) {
    return
  }
  await getMoneyData()
})

const amount = ref()

const amountOption = ref({
  visualMap: {
    show: false,
    type: 'continuous',
    seriesIndex: 0,
    min: 0,
    max: 200
  },
  title: {
    left: 'center',
    text: '账单数量统计'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      label: {
        backgroundColor: '#6a7985'
      }
    }
  },
  toolbox: {
    feature: {
      saveAsImage: {}
    }
  },
  grid: {
    left: '5%',
    right: '5.5%',
    bottom: '5%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: '' // 设置日期数组
  },
  yAxis: {
    type: 'value'
  },
  series: {
    name: '金额',
    type: 'line',
    areaStyle: {},
    data: '' // 设置数量数组
  }
})

const amountDate = ref(new Date().setHours(0, 0, 0, 0))
const amountRange = ref(7)
const amountStatus = ref('')

const amountChart = ref()

const getAmountData = async () => {
  amountChart.value.showLoading()

  const response = await billAmountDataService({
    createTime: amountDate.value,
    range: amountRange.value,
    status: amountStatus.value
  })
  amountOption.value.xAxis.data = response.data.map((item) => {
    let date = new Date(item.date)
    let year = date.getFullYear()
    let month = (1 + date.getMonth()).toString().padStart(2, '0')
    let day = date.getDate().toString().padStart(2, '0')
    return `${year}-${month}-${day}`
  })
  amountOption.value.series.data = response.data.map((item) => item.count)

  var range = () => {
    if (amountRange.value === 7) {
      return '一周内'
    } else if (amountRange.value === 14) {
      return '两周内'
    } else if (amountRange.value === 30) {
      return '一个月内'
    }
  }
  amountOption.value.title.text = `账单数量统计--${range()}`
  amountChart.value.hideLoading()
  amountChart.value.setOption(amountOption.value)
}

watch(amountRange, async () => {
  await getAmountData()
})

watch(amountDate, async (newValue) => {
  if (newValue === null) {
    return
  }
  await getAmountData()
})

watch(amountStatus, async () => {
  if (amountDate.value === null) {
    return
  }
  await getAmountData()
})

onMounted(async () => {
  moneyChart.value = echarts.init(money.value)
  await getMoneyData()

  amountChart.value = echarts.init(amount.value)
  await getAmountData()

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

const handleResize = () => {
  // todo 无效
  // 等待 DOM 更新完成后再调用 resize 方法
  nextTick(() => {
    if (moneyChart.value) {
      moneyChart.value.resize()
    }
    if (amountChart.value) {
      amountChart.value.resize()
    }
  })
}

onUnmounted(() => {
  // 组件卸载时移除事件监听器
  window.removeEventListener('resize', handleResize)
})
</script>

<template>
  <el-container>
    <el-main>
      <el-row>
        <el-col :span="12">
          <div class="table-header">
            <el-date-picker
              v-model="moneyDate"
              placeholder="请选择时间"
              type="date"
              format="YYYY-MM-DD"
              value-format="x"
              style="width: 130px"
            />

            <div>
              <el-button type="primary" @click="moneyRange = 7">
                一周内
              </el-button>
              <el-button type="primary" @click="moneyRange = 14">
                两周内
              </el-button>
              <el-button type="primary" @click="moneyRange = 30">
                一个月内
              </el-button>
            </div>
          </div>

          <div class="chart" ref="money"></div>
        </el-col>

        <el-col :span="12">
          <div class="table-header">
            <el-date-picker
              v-model="amountDate"
              placeholder="请选择时间"
              type="date"
              format="YYYY-MM-DD"
              value-format="x"
              style="width: 130px"
            />

            <el-select
              v-model="amountStatus"
              placeholder="请选择订单状态"
              clearable
              style="width: 160px"
            >
              <el-option label="完成" value="paid" />
              <el-option label="未完成" value="unpaid" />
            </el-select>

            <div>
              <el-button type="primary" @click="amountRange = 7">
                一周内
              </el-button>
              <el-button type="primary" @click="amountRange = 14">
                两周内
              </el-button>
              <el-button type="primary" @click="amountRange = 30">
                一个月内
              </el-button>
            </div>
          </div>

          <div class="chart" ref="amount"></div>
        </el-col>
      </el-row>
    </el-main>
  </el-container>
</template>

<style lang="scss" scoped>
.el-container {
  height: 100%;

  .el-main {
    height: 100%;
    padding: 0;

    .el-row {
      height: 100%;
      width: 100%;

      .el-col {
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        padding: 0 10px;

        .table-header {
          display: flex;
          justify-content: space-between;
          margin-bottom: 20px;
        }

        .chart {
          height: 80%;
          width: 100%;
        }
        //todo 响应式大小
      }
    }
  }
}
</style>
